using System;
using System.ComponentModel.DataAnnotations;
using Volo.Abp.Domain.Entities.Auditing;
using Volo.Abp.MultiTenancy;

namespace MatrixFramework.Shared.Domain.Photos.Tags
{
    /// <summary>
    /// 照片标签映射实体
    /// 表示照片与标签的多对多关系
    /// </summary>
    public class PhotoTagMapping : FullAuditedEntity<Guid>, IMultiTenant
    {
        /// <summary>
        /// 租户ID
        /// </summary>
        public virtual Guid? TenantId { get; protected set; }

        /// <summary>
        /// 照片ID
        /// </summary>
        public virtual Guid PhotoId { get; protected set; }

        /// <summary>
        /// 标签ID
        /// </summary>
        public virtual Guid TagId { get; protected set; }

        /// <summary>
        /// 标签来源
        /// </summary>
        public virtual TagSource Source { get; protected set; }

        /// <summary>
        /// 标签置信度（0-1）
        /// </summary>
        public virtual double Confidence { get; protected set; }

        /// <summary>
        /// 标签权重
        /// </summary>
        public virtual double Weight { get; protected set; }

        /// <summary>
        /// 是否为主要标签
        /// </summary>
        public virtual bool IsPrimary { get; protected set; }

        /// <summary>
        /// 是否已验证
        /// </summary>
        public virtual bool IsVerified { get; protected set; }

        /// <summary>
        /// 是否需要审核
        /// </summary>
        public virtual bool NeedsReview { get; protected set; }

        /// <summary>
        /// 标签添加时间
        /// </summary>
        public virtual DateTime TaggedTime { get; protected set; }

        /// <summary>
        /// 标签添加者ID
        /// </summary>
        public virtual Guid? TaggedBy { get; protected set; }

        /// <summary>
        /// 标签添加者名称
        /// </summary>
        [MaxLength(200)]
        public virtual string TaggedByName { get; protected set; }

        /// <summary>
        /// 标签备注
        /// </summary>
        [MaxLength(500)]
        public virtual string Notes { get; protected set; }

        /// <summary>
        /// 标签元数据
        /// </summary>
        public virtual Dictionary<string, object> Metadata { get; protected set; }

        /// <summary>
        /// AI分析信息
        /// </summary>
        public virtual TagAIInfo AIInfo { get; protected set; }

        /// <summary>
        /// 照片导航属性
        /// </summary>
        public virtual Photo Photo { get; protected set; }

        /// <summary>
        /// 标签导航属性
        /// </summary>
        public virtual PhotoTag Tag { get; protected set; }

        protected PhotoTagMapping()
        {
            Metadata = new Dictionary<string, object>();
            AIInfo = new TagAIInfo();
        }

        public PhotoTagMapping(
            Guid id,
            Guid photoId,
            Guid tagId,
            TagSource source = TagSource.Manual,
            double confidence = 1.0,
            Guid? tenantId = null) : base(id)
        {
            PhotoId = photoId;
            TagId = tagId;
            Source = source;
            Confidence = Math.Max(0, Math.Min(1, confidence));
            Weight = 1.0;
            TaggedTime = DateTime.Now;
            TenantId = tenantId;

            Metadata = new Dictionary<string, object>();
            AIInfo = new TagAIInfo();

            // AI标签默认需要验证
            if (source == TagSource.AI)
            {
                NeedsReview = true;
                IsVerified = false;
            }
            else
            {
                NeedsReview = false;
                IsVerified = true;
            }
        }

        /// <summary>
        /// 更新置信度
        /// </summary>
        public virtual void UpdateConfidence(double confidence)
        {
            Confidence = Math.Max(0, Math.Min(1, confidence));
        }

        /// <summary>
        /// 更新权重
        /// </summary>
        public virtual void UpdateWeight(double weight)
        {
            Weight = Math.Max(0, weight);
        }

        /// <summary>
        /// 设置为主要标签
        /// </summary>
        public virtual void SetAsPrimary()
        {
            IsPrimary = true;
        }

        /// <summary>
        /// 取消主要标签状态
        /// </summary>
        public virtual void UnsetAsPrimary()
        {
            IsPrimary = false;
        }

        /// <summary>
        /// 标记为已验证
        /// </summary>
        public virtual void MarkAsVerified()
        {
            IsVerified = true;
            NeedsReview = false;
        }

        /// <summary>
        /// 标记为需要审核
        /// </summary>
        public virtual void MarkAsNeedsReview()
        {
            NeedsReview = true;
            IsVerified = false;
        }

        /// <summary>
        /// 更新来源
        /// </summary>
        public virtual void UpdateSource(TagSource source)
        {
            Source = source;
        }

        /// <summary>
        /// 设置添加者信息
        /// </summary>
        public virtual void SetTaggedBy(Guid? taggedBy, string taggedByName)
        {
            TaggedBy = taggedBy;
            TaggedByName = taggedByName;
        }

        /// <summary>
        /// 更新备注
        /// </summary>
        public virtual void UpdateNotes(string notes)
        {
            Notes = notes;
        }

        /// <summary>
        /// 更新元数据
        /// </summary>
        public virtual void UpdateMetadata(Dictionary<string, object> metadata)
        {
            Metadata = metadata ?? new Dictionary<string, object>();
        }

        /// <summary>
        /// 设置元数据项
        /// </summary>
        public virtual void SetMetadata(string key, object value)
        {
            Metadata[key] = value;
        }

        /// <summary>
        /// 移除元数据项
        /// </summary>
        public virtual void RemoveMetadata(string key)
        {
            Metadata.Remove(key);
        }

        /// <summary>
        /// 更新AI信息
        /// </summary>
        public virtual void UpdateAIInfo(TagAIInfo aiInfo)
        {
            AIInfo = aiInfo ?? new TagAIInfo();
        }

        /// <summary>
        /// 检查是否可以编辑
        /// </summary>
        public virtual bool CanEdit()
        {
            return Source != TagSource.System;
        }

        /// <summary>
        /// 检查是否可以删除
        /// </summary>
        public virtual bool CanDelete()
        {
            return Source != TagSource.System;
        }

        /// <summary>
        /// 检查是否为高质量标签
        /// </summary>
        public virtual bool IsHighQuality()
        {
            return Confidence >= 0.8 && IsVerified;
        }

        /// <summary>
        /// 检查是否为AI生成的标签
        /// </summary>
        public virtual bool IsAITag()
        {
            return Source == TagSource.AI || Source == TagSource.Auto;
        }

        /// <summary>
        /// 计算标签评分
        /// </summary>
        public virtual double CalculateScore()
        {
            double score = Confidence * Weight;

            if (IsVerified)
                score *= 1.2;

            if (IsPrimary)
                score *= 1.5;

            if (Source == TagSource.Manual)
                score *= 1.1;

            return score;
        }
    }

    /// <summary>
    /// 标签来源枚举
    /// </summary>
    public enum TagSource
    {
        /// <summary>
        /// 手动添加
        /// </summary>
        Manual = 0,

        /// <summary>
        /// AI识别
        /// </summary>
        AI = 1,

        /// <summary>
        /// 自动生成
        /// </summary>
        Auto = 2,

        /// <summary>
        /// 系统生成
        /// </summary>
        System = 3,

        /// <summary>
        /// 批量导入
        /// </summary>
        BulkImport = 4,

        /// <summary>
        /// API添加
        /// </summary>
        API = 5,

        /// <summary>
        /// 第三方集成
        /// </summary>
        ThirdParty = 6,

        /// <summary>
        /// 用户推荐
        /// </summary>
        UserRecommendation = 7,

        /// <summary>
        /// 机器学习
        /// </summary>
        MachineLearning = 8,

        /// <summary>
        /// 规则引擎
        /// </summary>
        RuleEngine = 9
    }

    /// <summary>
    /// 标签AI信息
    /// </summary>
    public class TagAIInfo
    {
        /// <summary>
        /// AI模型名称
        /// </summary>
        [MaxLength(100)]
        public string ModelName { get; set; }

        /// <summary>
        /// AI模型版本
        /// </summary>
        [MaxLength(50)]
        public string ModelVersion { get; set; }

        /// <summary>
        /// 分析时间
        /// </summary>
        public DateTime AnalysisTime { get; set; }

        /// <summary>
        /// 分析耗时（毫秒）
        /// </summary>
        public long AnalysisDuration { get; set; }

        /// <summary>
        /// 原始置信度
        /// </summary>
        public double RawConfidence { get; set; }

        /// <summary>
        /// 调整后置信度
        /// </summary>
        public double AdjustedConfidence { get; set; }

        /// <summary>
        /// 特征向量
        /// </summary>
        public byte[] FeatureVector { get; set; }

        /// <summary>
        /// 检测区域
        /// </summary>
        public List<DetectionRegion> DetectionRegions { get; set; } = new();

        /// <summary>
        /// 上下文信息
        /// </summary>
        public Dictionary<string, object> Context { get; set; } = new();

        /// <summary>
        /// 相关标签
        /// </summary>
        public List<string> RelatedTags { get; set; } = new();

        /// <summary>
        /// 排除标签
        /// </summary>
        public List<string> ExcludedTags { get; set; } = new();

        /// <summary>
        /// AI处理阶段
        /// </summary>
        public AIProcessingStage ProcessingStage { get; set; }

        /// <summary>
        /// 质量评分
        /// </summary>
        public double QualityScore { get; set; }

        /// <summary>
        /// 可靠性评分
        /// </summary>
        public double ReliabilityScore { get; set; }

        /// <summary>
        /// 是否需要人工审核
        /// </summary>
        public bool RequiresHumanReview { get; set; }

        /// <summary>
        /// 审核建议
        /// </summary>
        [MaxLength(500)]
        public string ReviewSuggestion { get; set; }
    }

    /// <summary>
    /// 检测区域
    /// </summary>
    public class DetectionRegion
    {
        /// <summary>
        /// 区域类型
        /// </summary>
        public DetectionRegionType RegionType { get; set; }

        /// <summary>
        /// 边界框
        /// </summary>
        public BoundingBox BoundingBox { get; set; }

        /// <summary>
        /// 区域置信度
        /// </summary>
        public double Confidence { get; set; }

        /// <summary>
        /// 区域属性
        /// </summary>
        public Dictionary<string, object> Attributes { get; set; } = new();
    }

    /// <summary>
    /// 检测区域类型
    /// </summary>
    public enum DetectionRegionType
    {
        /// <summary>
        /// 整个图像
        /// </summary>
        FullImage = 0,

        /// <summary>
        /// 人脸区域
        /// </summary>
        Face = 1,

        /// <summary>
        /// 物体区域
        /// </summary>
        Object = 2,

        /// <summary>
        /// 文字区域
        /// </summary>
        Text = 3,

        /// <summary>
        /// 场景区域
        /// </summary>
        Scene = 4,

        /// <summary>
        /// 颜色区域
        /// </summary>
        Color = 5,

        /// <summary>
        /// 纹理区域
        /// </summary>
        Texture = 6,

        /// <summary>
        /// 自定义区域
        /// </summary>
        Custom = 7
    }

    /// <summary>
    /// AI处理阶段
    /// </summary>
    public enum AIProcessingStage
    {
        /// <summary>
        /// 初始检测
        /// </summary>
        InitialDetection = 0,

        /// <summary>
        /// 特征提取
        /// </summary>
        FeatureExtraction = 1,

        /// <summary>
        /// 分类识别
        /// </summary>
        Classification = 2,

        /// <summary>
        /// 置信度校准
        /// </summary>
        ConfidenceCalibration = 3,

        /// <summary>
        /// 上下文分析
        /// </summary>
        ContextAnalysis = 4,

        /// <summary>
        /// 后处理
        /// </summary>
        PostProcessing = 5,

        /// <summary>
        /// 质量检查
        /// </summary>
        QualityCheck = 6,

        /// <summary>
        /// 完成
        /// </summary>
        Completed = 7,

        /// <summary>
        /// 失败
        /// </summary>
        Failed = 8
    }

    /// <summary>
    /// 边界框
    /// </summary>
    public class BoundingBox
    {
        /// <summary>
        /// X坐标
        /// </summary>
        public double X { get; set; }

        /// <summary>
        /// Y坐标
        /// </summary>
        public double Y { get; set; }

        /// <summary>
        /// 宽度
        /// </summary>
        public double Width { get; set; }

        /// <summary>
        /// 高度
        /// </summary>
        public double Height { get; set; }

        /// <summary>
        /// 获取中心点X坐标
        /// </summary>
        public double CenterX => X + Width / 2;

        /// <summary>
        /// 获取中心点Y坐标
        /// </summary>
        public double CenterY => Y + Height / 2;

        /// <summary>
        /// 获取面积
        /// </summary>
        public double Area => Width * Height;

        /// <summary>
        /// 检查点是否在边界框内
        /// </summary>
        public bool ContainsPoint(double x, double y)
        {
            return x >= X && x <= X + Width && y >= Y && y <= Y + Height;
        }

        /// <summary>
        /// 计算与另一个边界框的交并比
        /// </summary>
        public double CalculateIoU(BoundingBox other)
        {
            if (other == null) return 0;

            double x1 = Math.Max(X, other.X);
            double y1 = Math.Max(Y, other.Y);
            double x2 = Math.Min(X + Width, other.X + other.Width);
            double y2 = Math.Min(Y + Height, other.Y + other.Height);

            if (x2 <= x1 || y2 <= y1) return 0;

            double intersection = (x2 - x1) * (y2 - y1);
            double union = Area + other.Area - intersection;

            return union > 0 ? intersection / union : 0;
        }
    }

    /// <summary>
    /// 标签推荐实体
    /// </summary>
    public class PhotoTagRecommendation : FullAuditedEntity<Guid>, IMultiTenant
    {
        /// <summary>
        /// 租户ID
        /// </summary>
        public virtual Guid? TenantId { get; protected set; }

        /// <summary>
        /// 照片ID
        /// </summary>
        public virtual Guid PhotoId { get; protected set; }

        /// <summary>
        /// 标签ID
        /// </summary>
        public virtual Guid TagId { get; protected set; }

        /// <summary>
        /// 推荐分数
        /// </summary>
        public virtual double RecommendationScore { get; protected set; }

        /// <summary>
        /// 推荐理由
        /// </summary>
        [MaxLength(1000)]
        public virtual string Reason { get; protected set; }

        /// <summary>
        /// 推荐类型
        /// </summary>
        public virtual RecommendationType Type { get; protected set; }

        /// <summary>
        /// 推荐来源
        /// </summary>
        public virtual RecommendationSource Source { get; protected set; }

        /// <summary>
        /// 是否已应用
        /// </summary>
        public virtual bool IsApplied { get; protected set; }

        /// <summary>
        /// 是否已拒绝
        /// </summary>
        public virtual bool IsRejected { get; protected set; }

        /// <summary>
        /// 应用时间
        /// </summary>
        public virtual DateTime? AppliedTime { get; protected set; }

        /// <summary>
        /// 拒绝时间
        /// </summary>
        public virtual DateTime? RejectedTime { get; protected set; }

        /// <summary>
        /// 用户反馈
        /// </summary>
        [MaxLength(500)]
        public virtual string UserFeedback { get; protected set; }

        /// <summary>
        /// 推荐元数据
        /// </summary>
        public virtual Dictionary<string, object> Metadata { get; protected set; }

        /// <summary>
        /// 照片导航属性
        /// </summary>
        public virtual Photo Photo { get; protected set; }

        /// <summary>
        /// 标签导航属性
        /// </summary>
        public virtual PhotoTag Tag { get; protected set; }

        protected PhotoTagRecommendation()
        {
            Metadata = new Dictionary<string, object>();
        }

        public PhotoTagRecommendation(
            Guid id,
            Guid photoId,
            Guid tagId,
            double recommendationScore,
            RecommendationType type,
            RecommendationSource source,
            Guid? tenantId = null) : base(id)
        {
            PhotoId = photoId;
            TagId = tagId;
            RecommendationScore = recommendationScore;
            Type = type;
            Source = source;
            TenantId = tenantId;

            Metadata = new Dictionary<string, object>();
        }

        /// <summary>
        /// 应用推荐
        /// </summary>
        public virtual void ApplyRecommendation(string userFeedback = null)
        {
            IsApplied = true;
            IsRejected = false;
            AppliedTime = DateTime.Now;
            UserFeedback = userFeedback;
        }

        /// <summary>
        /// 拒绝推荐
        /// </summary>
        public virtual void RejectRecommendation(string userFeedback = null)
        {
            IsRejected = true;
            IsApplied = false;
            RejectedTime = DateTime.Now;
            UserFeedback = userFeedback;
        }

        /// <summary>
        /// 重置推荐状态
        /// </summary>
        public virtual void ResetStatus()
        {
            IsApplied = false;
            IsRejected = false;
            AppliedTime = null;
            RejectedTime = null;
            UserFeedback = null;
        }

        /// <summary>
        /// 更新推荐分数
        /// </summary>
        public virtual void UpdateScore(double score)
        {
            RecommendationScore = Math.Max(0, Math.Min(1, score));
        }

        /// <summary>
        /// 更新推荐理由
        /// </summary>
        public virtual void UpdateReason(string reason)
        {
            Reason = reason;
        }

        /// <summary>
        /// 检查是否可以处理
        /// </summary>
        public virtual bool CanProcess()
        {
            return !IsApplied && !IsRejected;
        }
    }

    /// <summary>
    /// 推荐类型枚举
    /// </summary>
    public enum RecommendationType
    {
        /// <summary>
        /// 基于内容的推荐
        /// </summary>
        ContentBased = 0,

        /// <summary>
        /// 协同过滤推荐
        /// </summary>
        Collaborative = 1,

        /// <summary>
        /// 基于相似性的推荐
        /// </summary>
        SimilarityBased = 2,

        /// <summary>
        /// 基于规则的推荐
        /// </summary>
        RuleBased = 3,

        /// <summary>
        /// 混合推荐
        /// </summary>
        Hybrid = 4,

        /// <summary>
        /// 热门推荐
        /// </summary>
        Popular = 5,

        /// <summary>
        /// 个性化推荐
        /// </summary>
        Personalized = 6,

        /// <summary>
        /// 时序推荐
        /// </summary>
        Temporal = 7
    }

    /// <summary>
    /// 推荐来源枚举
    /// </summary>
    public enum RecommendationSource
    {
        /// <summary>
        /// AI模型
        /// </summary>
        AIModel = 0,

        /// <summary>
        /// 机器学习
        /// </summary>
        MachineLearning = 1,

        /// <summary>
        /// 用户行为分析
        /// </summary>
        UserBehavior = 2,

        /// <summary>
        /// 内容分析
        /// </summary>
        ContentAnalysis = 3,

        /// <summary>
        /// 规则引擎
        /// </summary>
        RuleEngine = 4,

        /// <summary>
        /// 统计分析
        /// </summary>
        StatisticalAnalysis = 5,

        /// <summary>
        /// 专家系统
        /// </summary>
        ExpertSystem = 6,

        /// <summary>
        /// 第三方服务
        /// </summary>
        ThirdPartyService = 7
    }
}